var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var WXPay = require('node-wxpay');
var fs = require('fs');
var wxpay = WXPay({
  appid: '公众号ID',
  mch_id: '商户号ID',
  partner_key: '商户密钥（证书密码）',
  pfx: fs.readFileSync('./证书路径.p12'),
});

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

app.use('/Receive/WxReceive1', function(req, res, next){
  console.log("test");
  res.send('respond with a resource');
});

// 原生支付回调
app.use('/Receive/WxReceiveNative', wxpay.useWXCallback(function(msg, req, res, next){
  // msg: 微信回调发送的数据
}));

// 支付结果异步通知
app.use('/Receive/WxReceive', wxpay.useWXCallback(function(msg, req, res, next){
  // 处理商户业务逻辑
  // res.success() 向微信返回处理成功信息，res.fail()返回失败信息。
  console.log("收到支付回调");
  console.log(msg);
  console.log(req);
  console.log(res);
  res.success();
}));

// 退款结果异步通知
app.use('/Receive/WxRefund', wxpay.useWXCallback(function(msg, req, res, next){
  // 处理商户业务逻辑
  // res.success() 向微信返回处理成功信息，res.fail()返回失败信息。
  console.log("收到退款回调");
  console.log(msg);
  console.log(req);
  console.log(res);
  res.success();
}));


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
